const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');
const { error } = require('../utils/response');

// 用户认证中间件
const authenticateToken = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    console.log('🔐 认证中间件 - 请求头:', authHeader ? authHeader.substring(0, 50) + '...' : '无');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      console.log('❌ 认证失败: 缺少或格式错误的Authorization头');
      return error(res, '请先登录', 401);
    }

    const token = authHeader.split(' ')[1];
    console.log('🔑 Token长度:', token ? token.length : 0);

    if (!token) {
      console.log('❌ 认证失败: Token为空');
      return error(res, '请先登录', 401);
    }

    const decoded = jwt.verify(token, secret);
    console.log('✅ Token验证成功, userId:', decoded.userId);

    req.userId = decoded.userId;
    req.userType = decoded.userType;
    next();
  } catch (err) {
    console.log('❌ Token验证失败:', err.message);
    if (err.name === 'TokenExpiredError') {
      return error(res, '登录已过期', 401);
    }
    return error(res, '认证失败', 401);
  }
};

// 管理员认证中间件
const authenticateAdmin = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return error(res, '请先登录', 401);
    }
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, secret);
    
    if (!decoded.isAdmin) {
      return error(res, '需要管理员权限', 403);
    }
    
    req.userId = decoded.userId;
    req.role = decoded.role;
    req.username = decoded.username || 'Unknown'; // 用于日志记录
    next();
  } catch (err) {
    if (err.name === 'TokenExpiredError') {
      return error(res, '登录已过期', 401);
    }
    return error(res, '认证失败', 401);
  }
};

// 导出
module.exports = authenticateToken; // 默认导出
module.exports.authenticateToken = authenticateToken;
module.exports.authenticateAdmin = authenticateAdmin;